package dao

import (
	"errors"
	"log"
)

type Message struct {
	ID         int64  `json:"id"`
	CustomerID int64  `json:"customer_id"`
	Sender     string `json:"sender"`
	Message    string `json:"message"`
	Timestamp  string `json:"timestamp"`
}

func InsertMessage(m Message) error {
	if db == nil {
		return errors.New("db is nil")
	}

	res, err := db.Exec("INSERT INTO message (customer_id, sender, message) VALUES (?, ?,?)", m.CustomerID,
		m.Sender, m.Message)
	if err != nil {
		log.Fatal(err)
	}
	id, _ := res.LastInsertId()
	log.Printf("Inserted message success. message:%v ID: %d", m, id)
	return nil
}

func GetMessageList(id int64, pageSize int, offset int) ([]Message, error) {
	if db == nil {
		return nil, errors.New("db is nil")
	}

	log.Printf("id:%v pageSize:%v offset:%v", id, pageSize, offset)

	rows, err := db.Query("SELECT id, customer_id, sender, message, timestamp FROM message WHERE customer_id = ? order by timestamp asc LIMIT ? OFFSET ?",
		id, pageSize, offset)
	if err != nil {
		log.Fatal("查询失败:", err)
	}
	defer rows.Close()

	log.Printf("rows: %v", rows)

	var messages []Message

	// 遍历结果
	for rows.Next() {
		var m Message
		// 将当前行数据扫描到变量中
		if err := rows.Scan(&m.ID, &m.CustomerID, &m.Sender, &m.Message, &m.Timestamp); err != nil {
			log.Fatal("读取数据失败:", err)
			continue
		}

		log.Println(m)
		messages = append(messages, m)
	}

	// 检查遍历过程中是否出错
	if err = rows.Err(); err != nil {
		log.Fatal("遍历结果时发生错误:", err)
	}

	log.Printf("messages: %v", messages)
	return messages, nil
}
